#!/usr/bin/env python
import pickle
import sqlite3

def read_inputfile(contactfile = 'contactinfo.dat', alnfile = 'tmp_aln.fasta'):
    #contactinfo.dat generate by ?
    with open(contactfile, 'rb') as pkl_file: 
        contactdat, pos_glgf, pos_gd = pickle.load(pkl_file)
    
        
        
        #pprint.pprint (contactdat)
        #raw_input()
        return contactdat, pos_glgf, pos_gd
    

def import_database(dbname, contactdat):
    mydb = sqlite3.connect('database/'+dbname)
    curs = mydb.cursor()
    table_name = 'test_contact'
    sql = """
          create table if not exists test_contact
          (peppos interger,
          motif varchar(4),
          offset interger,
          PDBID varchar(4),
          RES varchar(1),
          dist real);"""
    curs.execute(sql)
    
    sql = "insert into test_contact values(?,?,?,?,?,?);"
    for peppos in contactdat:
        for motif, offset in contactdat[peppos]:
            for pdbid, res, dist in contactdat[peppos][(motif,offset)]:
                dist = float(dist)
                curs.execute(sql, (peppos, motif, offset, pdbid, res, dist))
    
    mydb.commit()
    mydb.close()

if __name__ == '__main__':
    dbname = 'pdzvalid.db'
    
    contactdat, pos_glgf, pos_gd = read_inputfile()
    import_database(dbname, contactdat)